package pathfinding;

import java.util.HashMap;
import java.util.Map;

import main.Coord;

class Node extends Coord implements Comparable {
	public double value = Double.POSITIVE_INFINITY;
	public Node source;
	public Map<Node, Double> neigh = new HashMap<Node, Double>();
	private double tol = 0.48;
	
	public Node(int x, int y) {
		super(x, y);
	}

	@Override
	public int compareTo(Object o) {
		Node n = (Node)o;
		if (value < n.value) {
			return 1;
		} else {
			return -1;
		}
	}
	
	public boolean see(Node n, boolean[][] map) {
		Node s = n.x<x? n: this;
		Node e = n.x<x? this: n;
		
		boolean tf = see(s.angle(e), s, e, map, 0.5, 0.5);
		return tf;
	}
	private boolean see(double angle, Node start, Node end, boolean[][] map, double x, double y) {
		if (start.equals(end) && !map[end.x][end.y]) {
			return true;
		}
		if (map[start.x][start.y]) {
			return false;
		}
		if ((x < tol && map[start.x-1][start.y]) ||
				(x > 1-tol && map[start.x+1][start.y]) ||
				(y < tol && map[start.x][start.y-1]) ||
				(y > 1-tol && (start.y+1 >= map[start.x].length || map[start.x][start.y+1]))) {
			return false;
		}
		
		
		double a1 = Math.atan((1-y)/(1-x));
		double a2 = -Math.atan(y/(1-x));
		
		double yy,xx;
		Node s = new Node(start.x, start.y);
		if (angle > a1) {	// roof
			yy=0;
			xx = x + (1-y)/Math.tan(angle);
			s.y++;
		} else if (angle >= a2) {	// wall
			xx = 0;
			yy = y + Math.tan(angle)*(1-x);
			s.x++;
		} else {	// floor
			yy = 1;
			xx = x - y/Math.tan(angle);
			s.y--;
		}
		return see(angle, s, end, map, xx, yy);
	}
	
	public void addNeigh(Node n) {
		neigh.put(n, distanceTo(n));
	}
	
	@Override
	public String toString() {
		return "["+super.toString()+"; "+value+"]";
	}
	
	public String path() {
		if (source == null) return super.toString();
		return super.toString() +" -> "+ source.path();
	}
}